package com.wxy.demo.thread;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 停止线程
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/9/8 14:41
 */
public class Demo1 {

    public static volatile boolean isInterrupt = false;

    public static void main(String[] args) throws InterruptedException {
        // 1.自定义中断标识
//        new Thread(() -> {
//            System.out.println("子线程执行中...");
//            while (!isInterrupt) {
//            }
//        }).start();
//        Thread.sleep(2000);
//        System.out.println("主线程：试图终止子线程...");
//        isInterrupt = true;
        // 2.interrupt中断线程
//        Thread thread = new Thread(() -> {
//            System.out.println("子线程执行中...");
//            while (true) {
//            }
//        });
//        thread.start();
//        Thread.sleep(2000);
//        System.out.println("主线程：试图终止子线程...");
//        thread.interrupt();
        // 3.stop停止线程
        Thread thread = new Thread(() -> {
            try {
                System.out.println("子线程thread执行中...");
//                while (true) {
//                }
                Thread.sleep(1000 * 3600);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                System.out.println("子线程停止.");
            }
        });
        thread.start();
        Thread.sleep(2000);
        System.out.println("主线程：试图终止子线程...");
        thread.stop();
        // 4.线程池
//        ExecutorService service = Executors.newFixedThreadPool(1);
//        Future<Object> future = service.submit(() -> {
//            System.out.println("子线程执行中...");
//            while (true) {
//            }
//        });
//        Thread.sleep(2000);
//        System.out.println("主线程：试图终止子线程...");
//        future.cancel(false);
        // 5.hutool
//        Thread thread = new Thread(() -> {
//            System.out.println("子线程thread执行中...");
//            while (true) {
//            }
//        });
//        thread.start();
//        Thread.sleep(2000);
//        System.out.println("主线程：试图终止子线程...");
//        ThreadUtil.interrupt(thread,true);
    }
}
